const mongoose = require('mongoose');
var User = require('../models/use.model');
var jwt = require('jsonwebtoken');


//口令
exports.login = function(req,res,next){
    User.findOne(req.body,function(err,results){
        if(!err){
            var user = JSON.parse(JSON.stringify(results._doc));
              delete user.password;
            jwt.sign({results},'mySecretString',(err,token)=>{
              user.token = token;
              res.json(user);
            })
        }else{
          throw err
        }
    })
}


//插入数据
exports.create = function(req, res, next) {
    const user = new User(req.body);
    user.save((err,pr) => {
        if(!err){
            console.log('插入数据成功')
        }
        res.end();
    })
}

//修改数据
exports.update = function(req,res,next){
    const id = req.params.id;
    User.findByIdAndUpdate(id,{$set: req.body},{new:false}).then(data=>{
    res.json(data);
    })
}
  //删除数据
exports.remove = function(req,res,next){
    const id = req.params.id;
    User.remove({_id:id},(err,data)=>{
      res.json(data);
    })
}
exports.removes = function(req,res,next){
  const ids = req.body.ids.split(',');
  if(ids.length>0){
    User.remove({_id: {$in: ids}}).then(data=>{
      res.json({"message":"数据已删除!"})
    })
  }
}
//查找指定的数据
exports.get = function(req,res,next){
    const id = req.params.id;
    User.findById(id).then(data=>{
      res.json(data);
    })
  }

exports.list = function(req,res,next){
    var page = req.body.page ? req.body.page : 1;
    var rows = req.body.rows ? req.body.rows : 10;
    var queryCondition = {};
    if(req.body.name && req.body.name.trim().length>0){
      queryCondition = {
          "name": new RegExp(req.body.name,'i')
        }
    }
    if(req.body.user && req.body.user.trim().length>0){
      queryCondition = {
          "user": new RegExp(req.body.user,'i')
        }
    }
    if(req.body.newsId && req.body.newsId.trim().length>0){
      queryCondition = {
        "newsId": req.body.newsId
      }
    }
    User.paginate(queryCondition, { page: +page, limit: +rows }, function(err, result) {
        result.rows = result.docs;
        delete result.docs;
       res.json(result);
      });
}


